<template>
  <div class="block-main2" v-if="isMobile">

    <!-- 移动端使用微信扫码，这里按钮可以保留或隐藏 -->
    <button @click="wechatScan" style="display: none;">微信扫码</button>
  </div>
  <div class="block-main" v-else>

  </div>
</template>
<script setup>
import '../../assets/css/shoudiantong.css'
import scanCode from '/src/utils/scanCode.js'
import {
  ref,
  onMounted
} from "vue";
import {
  useRouter
} from "vue-router";
import {
  QrcodeStream,
  QrcodeCapture,
} from "vue-qrcode-reader";
import {
  showToast,
  showDialog
} from "vant";
import {
  checkEntity,getJsSdkConfig
} from "@/api/deviceEntity";
import jsQR from 'jsqr';
import {
  getUserid
} from '@/utils/auth';
// 引入 wx.js 文件
import '@/api/wx.js';
import wx from 'weixin-jsapi';
import weixinScanQRCode from "/src/utils/scanCode.js";

const isMobile = ref(false);
const qrStreamKey = ref(0); // 添加key值用于强制重新渲染组件
const hasCameraPermission = ref(false);

const torchActive = ref(false);
const hasTorch = ref(false);
let mediaStreamTrack = null;

const toggleTorch = async () => {
  // 首先检查是否是iOS设备
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

  if (isIOS) {
    // iOS设备使用不同的方法检测手电筒
    try {
      // 检查是否在支持的环境中（通常需要HTTPS）
      if (!('mediaDevices' in navigator)) {
        showToast('当前环境不支持手电筒功能');
        return;
      }

      // 尝试获取视频设备
      const devices = await navigator.mediaDevices.enumerateDevices();
      const videoDevices = devices.filter(device => device.kind === 'videoinput');

      if (videoDevices.length === 0) {
        showToast('没有找到摄像头设备');
        return;
      }

      // 尝试打开手电筒
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {facingMode: 'environment'}
      });

      const track = stream.getVideoTracks()[0];
      const capabilities = track.getCapabilities();

      if (!capabilities.torch) {
        showToast('当前设备不支持手电筒');
        return;
      }

      // 切换手电筒状态
      await track.applyConstraints({
        advanced: [{torch: !torchActive.value}]
      });

      torchActive.value = !torchActive.value;
      mediaStreamTrack = track; // 保存track引用以便后续操作
    } catch (error) {
      console.error('手电筒控制失败:', error);
      showToast('手电筒控制失败');
    }
  } else {
    // 原有Android设备检测逻辑
    if (!hasTorch.value) {
      showToast('当前设备不支持闪光灯');
      return;
    }

    try {
      if (mediaStreamTrack) {
        const capabilities = mediaStreamTrack.getCapabilities();
        if (capabilities.torch) {
          await mediaStreamTrack.applyConstraints({
            advanced: [{
              torch: !torchActive.value
            }]
          });
          torchActive.value = !torchActive.value;
        }
      }
    } catch (error) {
      console.error('闪光灯控制失败:', error);
      showToast('闪光灯控制失败');
    }
  }
};

// onMounted(async () => {
//   isMobile.value = /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);
//
//   try {
//     const stream = await navigator.mediaDevices.getUserMedia({
//       video: {
//         facingMode: 'environment'
//       }
//     });
//     const [track] = stream.getVideoTracks();
//     mediaStreamTrack = track;
//
//     // 检测设备是否支持闪光灯
//     const capabilities = track.getCapabilities();
//     hasTorch.value = !!capabilities.torch;
//
//   } catch (error) {
//     console.error('摄像头检测失败:', error);
//     hasTorch.value = false;
//   }
// });

const router = useRouter();

const params = ref({
  userId: getUserid(),
  deviceNumber: ''
});

const scanCodeTo = async () => {
// 获取当前页面的完整 URL
//   const currentUrl = window.location.href;
//   const currentUrl = "https://web.jmhyl.com/#/scanCode1";
  const currentUrl = window.location.href.split('#')[0];  // 去除 # 及后面的部分
  try {
    const response = await getJsSdkConfig({url: currentUrl});
    // 处理后端返回的 JsSdk 配置
    console.log('JsSdk 配置:', response.data);
    var data = {
      appId: response.data.appId,
      needResult: true,
      timestamp: response.data.timestamp,
      nonceStr: response.data.nonceStr,
      signature: response.data.signature,
    }
    console.log("scanCodeTo:data:",data)
    scanCode(data).then(async (res) => {
      try {
        const url = new URL(res);
        const deviceNumber = url.searchParams.get('deviceNumber');
        if (!deviceNumber) {
          showToast("二维码中未包含设备编号");
          // 更新key值，强制重新渲染组件
          qrStreamKey.value++;
          return;
        }
        params.value.deviceNumber = deviceNumber;

        const response = await checkEntity(params.value);
        if (response.status == 200) {
          router.replace({
            name: 'binding',
            params: {
              deviceNumber: deviceNumber
            }
          });
        } else {
          showToast({
            type: 'fail',
            message: response.desc || '识别二维码内容失败',
            forbidClick: true,
            duration: 1000
          });
          router.replace('/homePage')
        }
      } catch (err) {
        //console.log('二维码解析错误:', err);
        showToast({
          type: 'fail',
          message: err.desc || '二维码解析失败',
          forbidClick: true,
          duration: 1000
        });
        scanCodeTo();
      }
    }).catch((err) => {
      console.log("wx==errerrerrerrerr")
      console.log(err);
      router.replace('/homePage')
    });
  } catch (error) {
    console.error('获取 JsSdk 配置失败:', error);
    router.replace('/homePage')
  }


};

onMounted( () => {
  scanCodeTo();

});



const onCameraReady = (res) => {
  //console.log(res)
  //console.log("摄像头准备好了");
};

//错误提示
const onError = (error) => {
  var message = '摄像头错误';
  if (error.name === "NotAllowedError") {
    message = '用户拒绝相机访问权限';
    // 清除授权状态
    hasCameraPermission.value = false;
    localStorage.removeItem('cameraPermission');
  } else if (error.name === "NotFoundError") {
    message = '未安装合适的摄像设备'
  } else if (error.name === "NotSupportedError") {
    message = '当前网页没有通过 HTTPS 或 localhost 安全协议提供服务'
  } else if (error.name === "NotReadableError") {
    message = '相机被占用了'
  } else if (error.name === "OverconstrainedError") {
    message = '尝试使用前置摄像头'
  } else if (error.name === "StreamApiNotSupportedError") {
    message = '浏览器似乎缺少功能'
  } else if (error.name === "InsecureContextError") {
    message = '当前网页没有通过 HTTPS 或 localhost 安全协议提供服务'
  } else {
    // 如果是其他错误，也清除授权状态
    hasCameraPermission.value = false;
    localStorage.removeItem('cameraPermission');
  }
  showDialog({
    title: '提示',
    message: message,
  }).then(() => {
    // 更新key值，强制重新渲染组件
    // qrStreamKey.value++;
  });
};



</script>
<style lang="scss" scoped>
.block-main {
  height: 100%;
  background: #fff;
  overflow: hidden;
  font-size: 16px;
}

.block-main2 {
  height: calc(100vh - 50px);
  overflow: hidden;
  font-size: 16px;
}

.qr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.scan-overlay {
  background-color: rgba(0, 0, 0, 0.7);
}

.qr-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #fff;
}

.scan-tips {
  margin-bottom: 20px;
  font-size: 16px;
}

.scan-desc {
  margin-top: 20px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.scan-box {
  position: relative;
  width: 100vw;
  height: 100%;
  background-color: transparent;
  overflow: hidden;

  :deep(.qrcode-stream) {
    width: 100%;
    height: 100%;
  }
}

.scan-line {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(to right, transparent, #07c160, transparent);
  animation: scanMove 3s ease-in-out infinite;
}

.scan-angle {
  position: absolute;
  width: 28px;
  height: 28px;
  border-color: #07c160;
  border-style: solid;
  border-width: 4px;
}

.scan-angle-lt {
  left: 0;
  top: 0;
  border-right: none;
  border-bottom: none;
}

.scan-angle-rt {
  right: 0;
  top: 0;
  border-left: none;
  border-bottom: none;
}

.scan-angle-lb {
  left: 0;
  bottom: 0;
  border-right: none;
  border-top: none;
}

.scan-angle-rb {
  right: 0;
  bottom: 0;
  border-left: none;
  border-top: none;
}

@keyframes scanMove {
  0% {
    top: 0;
    opacity: 1;
  }
  50% {
    opacity: 0.8;
  }
  100% {
    top: 100%;
    opacity: 1;
  }
}

.custom-upload {
  display: inline-block;
  padding: 10px 20px;
  background-color: #1989fa;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.hidden-input {
  display: none;
}

.torch-button {
  position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.15);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 1000;
  backdrop-filter: blur(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.torch-button:hover {
  background: rgba(255, 255, 255, 0.25);
}

.torch-icon {
  font-size: 28px;
  color: #fff;
  transition: all 0.3s ease;
}

.torch-icon.fa-flashlight-on {
  color: #FFD700;
  filter: drop-shadow(0 0 8px rgba(255, 215, 0, 0.6));
}
</style>
